package com.pro.framework.api;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LinearEquationSolver {
    public static double solve(String equation) {
        equation = equation.replaceAll("\\s+", ""); // 去除空格

        // 确保格式正确
        if (!equation.contains("=")) {
            throw new IllegalArgumentException("方程格式错误，应包含 '='");
        }

        String[] sides = equation.split("=");
        if (sides.length != 2) {
            throw new IllegalArgumentException("方程格式错误，应为 'ax + b = c'");
        }

        String left = sides[0]; // ax + b
        String right = sides[1]; // c（可能不是 0，需要移项）

        // 提取 a 和 b
        double[] coefficients = extractCoefficients(left);
        double a = coefficients[0];
        double b = coefficients[1] - evaluateExpression(right); // 右侧移项相当于减去右边的值

        // 解方程
        if (a == 0) {
            if (b == 0) {
                throw new ArithmeticException("方程有无穷多解");
            } else {
                throw new ArithmeticException("方程无解");
            }
        }
        return -b / a;
    }

    /**
     * 提取 ax + b 形式的系数
     */
    private static double[] extractCoefficients(String expression) {
        double a = 0, b = 0;
        Pattern pattern = Pattern.compile("([-+]?\\d*\\.?\\d*)x|([-+]?\\d+\\.?\\d*)");
        Matcher matcher = pattern.matcher(expression);

        while (matcher.find()) {
            if (matcher.group(1) != null) { // x 的系数
                String coefficient = matcher.group(1);
                if (coefficient.equals("+") || coefficient.isEmpty()) {
                    a += 1;
                } else if (coefficient.equals("-")) {
                    a -= 1;
                } else {
                    a += Double.parseDouble(coefficient);
                }
            } else if (matcher.group(2) != null) { // 常数项
                b += Double.parseDouble(matcher.group(2));
            }
        }
        return new double[]{a, b};
    }

    /**
     * 计算表达式（用于右侧求值）
     */
    private static double evaluateExpression(String expression) {
        expression = expression.replaceAll("\\s+", ""); // 清理空格
        if (expression.isEmpty()) return 0;

        double result = 0;
        String[] terms = expression.split("(?=[+-])"); // 以正负号拆分
        for (String term : terms) {
            if (!term.isEmpty() && !term.contains("x")) { // 只解析数字，跳过 x
                result += Double.parseDouble(term);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String equation1 = "2x + 5 = 0";  // 结果: -2.5
        String equation2 = "-3x + 7 = 4"; // 结果: 1
        String equation3 = "x - 4 = 2x + 1"; // 结果: -5
        String equation4 = "0x + 0 = 0"; // 无穷多解
        String equation5 = "0x + 5 = 0"; // 无解
        String equation6 = "-x + 3 = 7"; // 结果: 4

        try {
            System.out.println("x = " + solve(equation1));
            System.out.println("x = " + solve(equation2));
            System.out.println("x = " + solve(equation3));
            System.out.println("x = " + solve(equation4));
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }

        try {
            System.out.println("x = " + solve(equation5));
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("x = " + solve(equation6));
    }
}
